<template>
  <base-breadcrumb v-loading="loading">
    <a-card
      :body-style="{ padding: '24px 32px' }"
      :bordered="false"
    >
      <a-tabs
        ref="tabs"
        v-model="nextSteps"
        @change="callback"
      >
        <a-tab-pane
          key="1"
          tab="基本信息"
        >
          <a-form-model
            ref="ruleForm"
            :model="form"
            :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
            :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
            :rules="rules"
          >
            <title-name title="考察分包商" />
            <a-row :gutter="24">
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="分包商名称"
                  prop="subcontractorName"
                >
                  <BaseInput
                    v-model="form.subcontractorName"
                    disabled
                    placeholder="请输入"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                v-if="!disabled"
                :md="10"
                :sm="10"
              >
                <div style="float:left">
                  <a-button
                    type="primary"
                    @click="choiceRecommand()"
                  >选择</a-button>
                  <span style="font-size:12px;margin-right:20px">(从推荐分包商中选择)</span>
                  <a-button
                    type="primary"
                    @click="choiceQualified()"
                  >选择</a-button>
                  <span style="font-size:12px;">(从合格分包商中选择)</span>
                </div>
              </a-col>
            </a-row>
            <a-row :gutter="24">
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="考察类型"
                  prop="investigateType"
                >
                  <a-select
                    v-model="form.investigateType"
                    :get-popup-container="getPopupContainer"
                    :disabled="disabled"
                    placeholder="请选择"
                    default-value=""
                    @change="changeType"
                  >
                    <a-select-option value="1">
                      服务类分包商考察
                    </a-select-option>
                    <a-select-option value="2">
                      甲指分包商考察
                    </a-select-option>
                    <a-select-option value="3">
                      劳务/专业分包商考察
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col
                :md="10"
                :sm="10"
              >
                <a-form-model-item
                  label="分公司"
                  prop="branchCompanyId"
                >
                  <SelectSubCompany
                    v-model="form.branchCompanyId"
                    :getAll="true"
                    :auto-selected="false"
                    placeholder="请选择"
                    :disabled="this.form.isQuality == false || disabled"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col
                :md="24"
                :sm="24"
              >
                <a-form-model-item
                  label="分包商类型"
                  prop="subcontractorsType"
                >
                  <a-tree-select
                    v-model="form.subcontractorsType"
                    tree-node-filter-prop="title"
                    style="width: 100%"
                    :disabled="this.form.isQuality == false || disabled"
                    multiple
                    :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
                    :replace-fields="{ children: 'children', key: 'id', value: 'id', title: 'name' }"
                    :tree-data="invesList"
                    placeholder="请选择/搜索"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
            <title-name title="考察小组" />
            <!-- <add-group></add-group> -->
            <div>
              <a-row>
                <div class="table-operator">
                  <a-row>
                    <a-col
                      :md="24"
                      :sm="24"
                    >
                      <a-button
                        v-if="!disabled"
                        type="primary"
                        @click="goAdd()"
                      >
                        新增小组成员
                      </a-button>
                      <a-button
                        v-if="!disabled"
                        :disabled="!selectedRowKeys.length"
                        type="info"
                        @click="goDel()"
                      >
                        删除
                      </a-button>
                    </a-col>
                  </a-row>
                </div>

                <a-table
                  :columns="columns"
                  bordered
                  :row-key="record => record.employeeId || record.id"
                  :row-selection="rowSelection"
                  :data-source="memberList"
                >
                  <span
                    slot="serial"
                    slot-scope="text, record, index"
                  >{{ index + 1 }}</span>
                  <template
                    slot="type"
                    slot-scope="text, record"
                  >
                    <span v-if="record.type">{{ ['组长', '成员'][record.type - 1] }}</span>
                  </template>

                  <span
                    slot="action"
                    slot-scope="text, record, index"
                  >
                    <template>
                      <a
                        v-if="!disabled"
                        @click="handleEditGroup(record, index)"
                      >编辑</a>
                    </template>
                  </span>
                </a-table>
              </a-row>
            </div>

            <title-name
              title="安全考察"
              class="mt20"
            />
            <a-row :gutter="24">
              <a-col
                :md="8"
                :sm="8"
                v-if="form.jobType === 'BC'"
              >
                <a-form-model-item label="安全考察人员所属分公司">
                  <BaseInput
                    v-model="form.invBranchComName"
                    disabled
                    placeholder="请输入"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item label="安全考察人员所属项目">
                  <BaseInput
                    v-model="form.invProjectName"
                    disabled
                    placeholder="请输入"
                    v-if="form.jobType === 'PD'"
                  />
                  <SelectProject
                    v-else
                    :disabled="disabled"
                    allowClear
                    @selectChange="onSelectChange1"
                    v-model="form.invProjectId"
                    placeholder="请选择"
                    :isEdit="form.id !== null"
                    :autoSelected="false"
                    :form="form"
                    key-value="invBranchComId"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="安全考察人员"
                  prop="invEmployeeId"
                >
                  <ASelectOrgPeople
                    v-show="form.invProjectId"
                    :disabled="disabled"
                    allowClear
                    @onSelectChange="form.invEmployeeName = $event.name"
                    :init="false"
                    :orgId="orgId1"
                    v-model="form.invEmployeeId"
                  ></ASelectOrgPeople>
                  <ASelectOrgPeople
                    v-show="!form.invProjectId"
                    :disabled="disabled"
                    allowClear
                    :request-params="{
                      and: true,
                      orgId: orgId1,
                      orgType: '2',
                    }"
                    @onSelectChange="form.invEmployeeName = $event.name"
                    :init="false"
                    :orgId="orgId1"
                    v-model="form.invEmployeeId"
                  ></ASelectOrgPeople>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
          <a-button
            style="float:right;margin:10px"
            type="primary"
            @click="nextStep()"
          >下一步</a-button>
        </a-tab-pane>
        <a-tab-pane
          key="2"
          tab="考察信息"
        >
          <div v-if="!disabled">
            <title-name title="考察信息填写链接" />
            <div style="display: flex;align-items: center;justify-content: flex-start;margin-bottom: 10px">
              <a-input
                v-model="shareUrls"
                placeholder=""
                disabled
                style="width: 50%;"
              />
              <a-button
                type="primary"
                style="margin-left: 5px;"
                @click="investigateShareReq"
              >
                生成链接
              </a-button>
              <a-button
                v-clipboard:copy="origins + shareUrls + '?id=' + uuid + '&access_token=' + token + '&type=' + types"
                v-clipboard:success="onCopy"
                v-clipboard:error="onError"
                type="primary"
                style="margin-left: 20px;"
              >
                复制链接
              </a-button>
            </div>
            <div style="margin-bottom: 10px;">
              注意：对方填写提交后，请刷新此页面获取填写数据；如果仍未获取到数据，请让对方再次提交，再次刷新此页面后获取数据。
            </div>
          </div>

          <!-- 服务 -->
          <service
            v-if="form.investigateType == '1' || form.investigateType == '服务类分包商考察'"
            ref="serverRef"
            :disabled="disabled"
            :service-list="serviceList"
            @submitNext="getsubmitNext"
            @validChanged="handleValidChanged"
          />
          <!-- 甲指 -->
          <Fingernail
            v-if="form.investigateType == '2' || form.investigateType == '甲指分包商考察'"
            ref="serverRef"
            :disabled="disabled"
            :fingernail-list="fingernailList"
            @submitNextSteps="getsubmitNextSteps"
            @validChanged="handleValidChanged"
          />
          <!-- 劳务 -->
          <labour
            v-if="form.investigateType == '3' || form.investigateType == '劳务/专业分包商考察'"
            ref="serverRef"
            :disabled="disabled"
            :labour-list="labourList"
            @submitNextStep="getsubmitNextStep"
            @validChanged="handleValidChanged"
          />
          <!-- <a-button style="float:right;" @click="nextStep()" type="primary">下一步</a-button> -->
        </a-tab-pane>
        <a-tab-pane
          key="3"
          tab="附件上传"
        >
          <u-table
            :upload-arrys="fileArrysDataList"
            business-code="PM09"
            :req-method="reqMethod"
            :list-url="listUrl"
            :is-show="!disabled"
            :upload-list="uploadList"
            :business-id="id"
            :delete-url="deleteUrl"
            :refresh-after-upload="false"
            @fileArrysData="fileArrysData"
          />
          <a-button
            v-if="type === 'kaocha' || type === 'view' || type === 'approve'"
            style="float:right;margin:10px"
            type="primary"
            @click="nextStep()"
          >
            下一步
          </a-button>
        </a-tab-pane>
        <a-tab-pane
          key="4"
          tab="安全考察情况"
          v-if="disabled"
        >
          <title-name title="基础信息" />
          <a-form-model
            ref="ruleForm2"
            :model="form"
            :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
            :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
            :rules="rules"
          >
            <a-row :gutter="24">
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item label="安全考察人员所属分公司">
                  <BaseInput
                    v-model="form.invBranchComName"
                    disabled
                    placeholder="请输入"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item label="安全考察人员所属项目">
                  <BaseInput
                    v-model="form.invProjectName"
                    disabled
                    placeholder="请输入"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item label="安全考察人员">
                  <BaseInput
                    v-model="form.invEmployeeName"
                    disabled
                    placeholder="请输入"
                  />
                </a-form-model-item>
              </a-col>
              <a-col
                :md="8"
                :sm="8"
              >
                <a-form-model-item
                  label="分包商单位级别"
                  prop="subUnitLevel"
                >
                  <BSelect
                    v-model="form.subUnitLevel"
                    :list="[
                    {id:'0',name:'一级'},
                    {id:'1',name:'二级'},
                    {id:'2',name:'三级'},
                  ]"
                    placeholder="请输入"
                    :disabled="disabled2"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>

            <title-name title="考核表" />
            <a-table
              :columns="scoreColumns"
              bordered
              row-key="id"
              :data-source="scoreList"
            >
              <template
                slot="input"
                slot-scope="text, record, index"
              >
                <b-input
                  class="requiredFormItem"
                  v-if="!disabled2"
                  v-model="record.situation"
                />
                <span v-else>{{ record.situation }}</span>
              </template>
            </a-table>

            <title-name
              title="安全考察人员意见"
              class="mt20"
            />
            <a-row :gutter="24">
              <a-col>
                <a-form-model-item
                  prop="inspectionSuggestion"
                  class="ttt"
                >
                  <BaseTextarea
                    :max="1000"
                    class="requiredFormItem"
                    :disabled="disabled2"
                    v-model="form.inspectionSuggestion"
                    placeholder="请输入"
                  />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-tab-pane>
      </a-tabs>
    </a-card>
    <div class="page-btn-right-top">
      <a-button
        v-if="type == 'add' || type == 'edit' || type == 'kaocha'"
        class="button ml12"
        type="primary"
        :loading="loadingSave"
        :disabled="loadingSubmit"
        @click="preSave"
      >
        保存草稿
      </a-button>
      <a-button
        v-if="type == 'add' || type == 'edit'|| type == 'kaocha'"
        class="button ml12"
        type="primary"
        :disabled="loadingSave"
        :loading="loadingSubmit"
        @click="preSubmit"
      >
        提交
      </a-button>
      <a-button
        class="button ml12"
        type="primary"
        @click="goBack"
      >
        关闭
      </a-button>
    </div>
    <!-- 推荐分包商 -->
    <a-modal
      v-model="visible"
      width="80%"
      title="选择推荐分包商"
      @ok="selectSub"
      @cancel="handleCancel"
    >
      <a-form-model :model="form">
        <a-row>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="推荐分包商"
              :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
            >
              <BaseInput
                v-model="searchQuery.recommendSubcontractors"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="入库状态"
              :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
            >
              <a-select
                v-model="searchQuery.isWarehousing"
                allow-clear
              >
                <a-select-option value="0">
                  已入库
                </a-select-option>
                <a-select-option value="1">
                  未入库
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="分公司"
              :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
            >
              <SelectSubCompany
                v-model="searchQuery.branchCompanyId"
                allow-clear
                :auto-selected="false"
                @change="handleChangeCompany"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="12"
            :sm="12"
          >
            <div style="float:right">
              <a-button
                style="margin:0 20px"
                type="primary"
                @click="getSubcontractorsLists()"
              >
                搜索
              </a-button>
              <a-button @click="getReset">
                重置
              </a-button>
            </div>
          </a-col>
        </a-row>
      </a-form-model>
      <a-table
        :columns="columns1"
        :row-selection="RecomSubRowSelection"
        :data-source="dataList"
        :loading="loadingState.isRecomd"
        :scroll="{ y: 500 }"
        row-key="id"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>

        <span
          slot="isWarehousing"
          slot-scope="text, record"
        >
          <span v-if="record.isWarehousing == '1'">未入库</span>
          <span v-if="record.isWarehousing == '0'">已入库</span>
        </span>
      </a-table>
      <pagination
        v-model="searchQuery.pageNo"
        :total="total"
        :page-size.sync="searchQuery.pageSize"
        @change="handlePageChangerem"
        @showSizeChange="showSizeChangerem"
      />
    </a-modal>

    <!-- 合格分包商 -->
    <a-modal
      v-model="qulVisible"
      width="80%"
      title="选择合格分包商"
      @ok="handleOkQul"
      @cancel="handleCancelQul"
    >
      <a-form :model="form">
        <a-row>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="分包商名称"
              :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
            >
              <BaseInput
                v-model="searchQueryQul.subcontractorName"
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="分公司"
              :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
            >
              <SelectSubCompany
                v-model="searchQueryQul.branchComId"
                allow-clear
                :auto-selected="false"
                @change="handleChangeCompany"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col
            :md="24"
            :sm="24"
          >
            <div style="float:right">
              <a-button
                style="margin:12px"
                type="primary"
                @click="getLaborSubcontractors"
              >
                搜索
              </a-button>
              <a-button @click="resetQuality">
                重置
              </a-button>
            </div>
          </a-col>
        </a-row>
      </a-form>
      <a-table
        :columns="columnsQul"
        :row-selection="QulRecomRowSelection"
        :data-source="dataListQul"
        :loading="loadingState.isQuality"
        :scroll="{ y: 500 }"
        row-key="id"
      >
        <span
          slot="serial"
          slot-scope="text, record, index"
        >{{ index + 1 }}</span>
      </a-table>
      <pagination
        v-model="searchQueryQul.pageNo"
        :total="qultotal"
        :page-size.sync="searchQueryQul.pageSize"
        @change="handlePageChangequl"
        @showSizeChange="showSizeChangequl"
      />
    </a-modal>
    <!-- 考察小组 -->
    <a-modal
      v-model="visibleGroup"
      width="60%"
      :confirm-loading="confirmLoading"
      :title="titles"
      @ok="handleOk"
      @cancel="handleCancelGroup"
    >
      <a-form-model
        ref="createModal"
        :model="formAdd"
        :rules="groupFormRules"
      >
        <a-row>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="考察人员"
              :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="employeeId"
            >
              <a-select
                v-model="employee"
                placeholder="请选择"
                show-search
                :filter-option="filterOption"
                :disabled="type == 'view'"
                :not-found-content="loadingUser ? loadingUser : null"
                label-in-value
                @search="handlerSearchEmployee"
                @change="changeMember"
                @popupScroll="scrollMore"
              >
                <a-icon
                  v-if="loadingUser"
                  slot="suffixIcon"
                  style="color: #096dd9"
                  type="loading"
                />
                <a-spin
                  v-if="loadingUser"
                  slot="notFoundContent"
                  size="small"
                />
                <a-select-option
                  v-for="item in groupLists"
                  :key="item.userId"
                >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col
            :md="12"
            :sm="12"
          >
            <a-form-model-item
              label="类别"
              :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
              prop="type"
            >
              <a-select
                v-model="formAdd.type"
                placeholder="请选择"
                :get-popup-container="getPopupContainer"
                :disabled="type == 'view'"
              >
                <a-select-option value="1">
                  组长
                </a-select-option>
                <a-select-option value="2">
                  成员
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col
            :md="24"
            :sm="24"
          >
            <a-form-model-item
              label="职位"
              :label-col="{ lg: { span: 6 }, sm: { span: 6 } }"
              :wrapper-col="{ lg: { span: 18 }, sm: { span: 18 } }"
            >
              <BaseInput
                v-model="formAdd.post"
                disabled
                placeholder="请输入"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <!-- 选择审批人 -->
    <selectApprover
      :business-id="businessId"
      :process-config="setProcessConfig"
    />
    <!-- 选择审批人 -->
  </base-breadcrumb>
</template>

<script>
import Vue from 'vue'
import { getAttachment, getContent, getHeaders } from '@/api/commons'
import { STable, Ellipsis } from '@/components'
import {
  basicInformation,
  getGroup,
  addbasicInformation,
  editbasicInformation,
  getbasicInformation,
  addLabourBasic,
  getInvestigateType,
  updateSubStatus,
  investigateShare,
  editfingernailList,
  editSituation
} from '@/api/subcontractors/subcontractors'
import { getPosts } from '@/api/design/plotsPlan'
import AddGroup from '@/views/subcontractors/investigate/components/AddGroup'
import Service from '@/views/subcontractors/investigate/components/Service'
import Fingernail from '@/views/subcontractors/investigate/components/Fingernail'
import Labour from '@/views/subcontractors/investigate/components/Labour'
import { getSubcontractorsLists } from '@/api/subcontractors'
import { getEmployeesList } from '@/api/system/menuAndAuth.js'
import { getlabourService, editlabourList } from '@/api/subcontractors/subcontractors'
import { getfingernailList, getServiceInformation, deleteSub, istheSameInvestigate } from '@/api/subcontractors/subcontractors'
import { editInformatinService } from '@/api/subcontractors/subcontractors'
import { getLaborSubcontractors } from '@/api/subcontractors/labor'
import { createValidTool } from '@/utils/regExpression'
import debounce from 'lodash/debounce'
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject'
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'

export default {
  name: 'Add',
  components: {
    STable,
    AddGroup,
    Service,
    Fingernail,
    Labour,
    SelectSubCompany,
    SelectProject,
    ASelectOrgPeople
  },
  props: {
    text: String
  },
  watch: {
    isAudit: {
      immediate: true,
      handler(val) {
        if (val) {
          this.type = 'view'
        }
      }
    },
    'form.invProjectId'(newVal) {
      if (!newVal) {
        this.form.orgId = ''
      }
      console.log('this.inited', this.inited, newVal)
      if (this.inited) {
        this.form.invEmployeeId = ''
      }
    }
  },
  data() {
    return {
      columns: [
        {
          title: '序号',
          width: 65,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '姓名',
          dataIndex: 'employeeName',
          ellipsis: true
        },
        {
          title: '职位',
          dataIndex: 'post',
          ellipsis: true
        },
        {
          title: '类别',
          dataIndex: 'type',
          scopedSlots: { customRender: 'type' },
          ellipsis: true
        },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      columns1: [
        {
          title: '序号',
          width: 65,
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '推荐分包商名称',
          dataIndex: 'recommendSubcontractors',
          ellipsis: true
        },
        {
          title: '推荐人',
          dataIndex: 'recommend',
          ellipsis: true
        },
        {
          title: '分公司',
          dataIndex: 'branchCompany',
          ellipsis: true
        },
        {
          title: '推荐项目',
          dataIndex: 'recommendProject',
          ellipsis: true
        },
        {
          title: '合作事项',
          dataIndex: 'cooperation',
          ellipsis: true
        },
        {
          title: '状态',
          dataIndex: 'isWarehousing',
          scopedSlots: { customRender: 'isWarehousing' }
        }
        // {
        //   title: '操作',
        //   dataIndex: 'action',
        //   scopedSlots: { customRender: 'action' }
        // }
      ],
      columnsQul: [
        {
          title: '序号',
          width: 65,
          dataIndex: 'name',
          scopedSlots: { customRender: 'serial' }
        },
        {
          title: '分包商名称',
          dataIndex: 'subcontractors',
          ellipsis: true
        },
        {
          title: '分公司',
          dataIndex: 'branch',
          ellipsis: true
        },
        {
          title: '分包商类型',
          dataIndex: 'type',
          ellipsis: true
        },
        {
          title: '等级',
          dataIndex: 'level',
          ellipsis: true
        },
        {
          title: '状态',
          dataIndex: 'statusName'
        }
      ],
      inited: true,
      handlerSearchEmployee: null,
      uuid: '',
      types: 'share',
      origins: '', // 路径前缀
      shareUrls: '', //  复制后的分享路径
      loadingState: {
        isRecomd: false,
        isQuality: false
      },
      token: '',
      total: 0,
      qulSurveyId: '', //从合格分包商选择的带出来的考察id
      visible: false,
      qulVisible: false,
      isSubmitOrSave: 'save',
      loading: false,
      loadingUser: false,
      loadingSubmit: false,
      loadingSave: false,
      nextSteps: '1',

      dataListQul: [],
      childValidInfo: createValidTool(), // 验证子组件信息
      confirmLoading: false,
      searchQueryQul: {
        pageNo: 1,
        pageSize: 10
      },
      idAddEdit: 0, //判断是新增的编辑还是编辑的编辑
      editTargetIndex: null, // 考察小组人员，编辑目标在表格中的序号
      searchQuery: {
        pageNo: 1,
        pageSize: 10
      },
      subcontractorName: '',
      subcontractorId: '',
      isSaveDraft: false,
      formAdd: {
        post: ''
      },
      list: [],
      // 附件上传
      listUrl: '/cscec-project-business/subcontractors-file/inspect/query',
      deleteUrl: '/cscec-project-business/subcontractors-file/inspect/delete',
      uploadList: '/cscec-project-business/subcontractors-file/inspect/upload',
      reqMethod: 'post',
      fileArrysDataList: [],
      title: '',
      labourList: {},

      pageNumber: 1,
      totalPages: 1,
      visibleGroup: false,

      form: {
        jobType: '',
        invBranchComId: '',
        invEmployeeId: '',
        invEmployeeName: '',
        investigateType: '',
        invProjectId: '',
        orgId: '',
        list: [],
        subcontractorsType: []
      },
      status: 'all',
      employee: '',
      titles: '',
      qultotal: 0,
      pageNo: 1,
      pageSize: 10,
      remtotal: 0,

      dataList: [],
      ifReplace: null, // 是否替换小组成员
      type: this.$route.query.type,
      groupLists: [],
      memberList: [],
      serviceList: {},
      typeList: [],
      fingernailList: {},
      id: '',
      selectedRows: [],
      selectedRowKeys: [],
      qulRecomSubselectedRowKeys: [],
      qulRecomSubselectedRows: [],
      RecomSubselectedRows: [],
      RecomSubselectedRowKeys: [],
      invesList: [],
      addInvestigateId: '',
      // 校验规则
      rules: {
        subcontractorName: [{ required: true, message: '请选择分包商名称', trigger: 'change' }],
        investigateType: [{ required: true, message: '请选择考察类型', trigger: 'change' }],
        subcontractorsType: [{ required: true, message: '请选择分包商类型', trigger: 'change' }],
        branchCompanyId: [{ required: true, message: '请选择分公司', trigger: 'change' }],
        invEmployeeId: [{ required: true, message: '请选择安全考察人员', trigger: 'change' }],
        subUnitLevel: [{ required: true, message: '请选择分包商单位级别', trigger: 'change' }],
        inspectionSuggestion: [{ required: true, message: '请填写安全考察人员意见', trigger: 'blur' }]
      },
      groupFormRules: {
        employeeId: [{ required: true, message: '请选择考察人员', trigger: 'change' }],
        type: [{ required: true, message: '请选择人员类型', trigger: 'change' }]
      },
      scoreColumns: [],
      scoreList: [],
      // 流程配置
      processConfig: null,
      //点击提交发送流程配置值
      setProcessConfig: null,
      // 业务id
      businessId: null
    }
  },
  async created() {
    //获取通过获取流程配置值
    this.processConfig = await this.$getConfigFn('labor_subcontract_inspect')
    this.addInvestigateId = JSON.parse(sessionStorage.getItem('addInvestigateId'))
    this.id = this.$route.query.id || this.addInvestigateId

    if (!this.id) {
      this.form.jobType = this.$currentPost().code
      if (this.form.jobType === 'BC') {
        this.form.invBranchComId = this.$currentPost().orgId
        this.form.invBranchComName = this.$currentPost().orgName
      }
      if (this.form.jobType === 'PD') {
        this.form.orgId = this.$currentPost().id
        this.form.invProjectId = this.$currentPost().projectId
        this.form.invProjectName = this.$currentPost().projectName
      }
    }

    if (this.$route.fullPath == '/project/subcontractors/investigate/view') {
      this.type = 'view'
    }

    this.handlerSearchEmployee = debounce((val) => {
      this.getOrgUsers(val)
    }, 800)

    this.getbasicInformation()
    this.getInvestigateType()

    if (this.type == 'edit' || this.type == 'add') {
      this.token = Vue.getAcloudProvider().getAccessToken()
      this.origins = location.origin
      this.getOrgUsers() // 获取考察人员列表
    }

    if (this.type == 'view') {
      this.confirmLoading = true
    } else {
      this.confirmLoading = false
    }

    // this.$refs.tabs.activeKey = this.nextSteps
    if (this.type == 'add') {
      this.idAddEdit = 0
    } else {
      this.idAddEdit = 1
    }
    if (this.type == 'kaocha') {
      this.nextSteps = '4'
    }
    // this.getScoreData()
  },
  destroyed() {
    let addInvestigateId = JSON.parse(sessionStorage.getItem('addInvestigateId'))
    if (addInvestigateId) {
      sessionStorage.removeItem('addInvestigateId')
    }
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        selectedRows: this.selectedRows, // 当前行所有数据
        onChange: this.onSelectChange
      }
    },
    //  选择推荐分包商
    RecomSubRowSelection() {
      return {
        type: 'radio',
        selectedRowKeys: this.RecomSubselectedRowKeys,
        selectedRows: this.RecomSubselectedRows, // 当前行所有数据
        onChange: this.RecomSubonSelectChange,
        getCheckboxProps: (record) => ({
          props: {
            // 禁止选中
            disabled: record.isWarehousing == '0' ? true : false
          }
        })
      }
    },
    // 选择合格分包商
    QulRecomRowSelection() {
      return {
        type: 'radio',
        selectedRowKeys: this.qulRecomSubselectedRowKeys,
        selectedRows: this.qulRecomSubselectedRows, // 当前行所有数据
        onChange: this.qulRecomSubonSelectChange
      }
    },
    orgId1() {
      return this.form.orgId || this.form.invBranchComId
    },
    disabled() {
      return this.type === 'view' || this.type === 'approve' || this.type === 'kaocha'
    },
    disabled2() {
      return this.type === 'view' || this.type === 'approve'
    }
  },
  methods: {
    async getScoreData2() {
      if (this.form.safetyInvestigationDTO) {
        this.scoreColumns = [
          { title: '考察内容', dataIndex: 'content', width: '20%' },
          { title: '考察要求', dataIndex: 'demand', width: '30%' },
          {
            title: '考察情况',
            width: '50%',
            dataIndex: 'situation',
            scopedSlots: { customRender: 'input' }
          }
        ]
        this.form.inspectionSuggestion = this.form.safetyInvestigationDTO.inspectionSuggestion
        this.scoreList = this.form.safetyInvestigationDTO.progressReviews
        this.form.subUnitLevel = this.form.safetyInvestigationDTO.subUnitLevel
      }
    },
    async getScoreData() {
      let header = await getHeaders({ formId: '824206605510905856' })
      if (header.code === 200) {
        this.scoreColumns = header.data
          .filter((v) => {
            if (v.title === '考核名称' || v.title === '主要检查内容/扣分标准' || v.title === '主要检查内容') {
              return true
            }
            return false
          })
          .map((v) => {
            if (v.title === '考核名称') {
              v.width = '20%'
              v.title = '考察内容'
            }
            if (v.title === '主要检查内容/扣分标准' || v.title === '主要检查内容') {
              v.width = '30%'
              v.title = '考察要求'
            }
            return v
          })
          .concat([
            {
              title: '考察情况',
              width: '50%',
              dataIndex: 'situation',
              scopedSlots: { customRender: 'input' }
            }
          ])
      }
      if (this.form.safetyInvestigationDTO) {
        this.form.inspectionSuggestion = this.form.safetyInvestigationDTO.inspectionSuggestion
        this.scoreList = this.form.safetyInvestigationDTO.progressReviews.map((v) => {
          let r2 = this.scoreColumns.find((w) => w.title === '考察内容')
          if (r2) {
            v[r2.dataIndex] = v.content
          }
          let r3 = this.scoreColumns.find((w) => w.title === '考察要求')
          if (r3) {
            v[r3.dataIndex] = v.demand
          }
          return v
        })
        this.form.subUnitLevel = this.form.safetyInvestigationDTO.subUnitLevel
      } else {
        let content = await getContent({ formId: '824206605510905856' })
        if (content.code === 200) {
          this.scoreList = content.data
        }
      }
      console.log(this.scoreList)
    },
    onSelectChange1(e) {
      console.log('e', e)
      // if (!this.isInit) return this.isInit = true
      this.form.orgId = e.projectDeptId
      this.form.invProjectName = e.name
    },
    investigateShareReq() {
      let that = this
      if (that.id != null) {
        investigateShare({ id: that.id }).then((res) => {
          if (res.data.code == 200) {
            that.uuid = res.data.message
            that.shareUrls = '/project/subcontractors/investigate/share'
          }
        })
      }
    },
    onCopy: function (e) {
      if (this.shareUrls == '') {
        this.$message.success('复制失败,请生成链接在进行复制！')
      }
      if (this.uuid != '' && this.shareUrls != '') {
        this.$message.success('复制成功，可直接去粘贴')
      }
    },
    onError: function (e) {
      if (this.shareUrls == '') {
        this.$message.success('复制失败,请生成链接在进行复制！')
      }
    },

    fileArrysData(val) {
      this.fileArrysDataList = val
    },
    handlePageChangerem(pageNo, pageSize) {
      this.searchQuery.pageNo = pageNo
      this.searchQuery.pageSize = pageSize
      this.getSubcontractorsLists()
    },
    handlePageChangequl(pageNo, pageSize) {
      this.searchQueryQul.pageNo = pageNo
      this.searchQueryQul.pageSize = pageSize
      this.getLaborSubcontractors()
    },
    showSizeChangequl(pageNo, pageSize) {
      this.searchQueryQul.pageNo = pageNo
      this.searchQueryQul.pageSize = pageSize
      this.getLaborSubcontractors()
    },
    showSizeChangerem(pageNo, pageSize) {
      this.searchQuery.pageNo = pageNo
      this.searchQuery.pageSize = pageSize
      this.getSubcontractorsLists()
    },
    handleValidChanged(data) {
      this.childValidInfo.update(data)
    },
    /**
     * 重置合格分包商的筛选条件
     */
    resetQuality() {
      this.searchQueryQul = {}
      this.getLaborSubcontractors()
    },
    // 保存考察信息草稿
    getsubmitNext(val) {
      if (this.type != 'view') {
        // 验证子组件是否有内容填写错误
        const validInfo = this.childValidInfo.validate()
        if (!validInfo.valid) {
          this.$message.warn(validInfo.message)
          this.nextSteps = '2'
          return false
        }
        this.nextSteps = '3'
        this.form.surveyId = this.id
        this.serviceList.investigateTypeCode = '1'
        // 当没有小组长时，不访问接口
        let groupLeader = this.memberList.filter((item) => item.type == '1')
        if (groupLeader.length !== 0) {
          editInformatinService(this.serviceList).then((res) => {
            if (res.code == 200 || res.data.code == 200) {
              this.getbasicInformation()
              this.$message.success('保存成功')
            }
          })
        }
      } else {
        this.nextSteps = '3'
      }
    },
    // 甲指
    getsubmitNextSteps(val) {
      if (this.type != 'view') {
        // 验证子组件是否有内容填写错误
        const validInfo = this.childValidInfo.validate()
        if (!validInfo.valid) {
          this.$message.warn(validInfo.message)
          this.nextSteps = '2'
          return false
        }
        this.nextSteps = '3'
        this.fingernailList.investigateTypeCode = '2'
        editfingernailList(this.fingernailList).then((res) => {
          if (res.code == 200 || res.data.code == 200) {
            this.getbasicInformation()

            this.$message.success('保存成功')
          }
        })
      } else {
        this.nextSteps = '3'
      }
    },
    // 劳务分包
    getsubmitNextStep(val) {
      // 验证子组件是否有内容填写错误
      const validInfo = this.childValidInfo.validate()
      if (!validInfo.valid) {
        this.$message.warn(validInfo.message)
        this.nextSteps = '2'
        return false
      }
      this.nextSteps = '3'
      this.labourList.investigateId = this.id
      this.labourList.investigateTypeCode = '3'
      this.labourList.lsebId = this.labourList.subcontractorBase.evaluationId
      if (this.type != 'view') {
        editlabourList(this.labourList).then((res) => {
          if (res.code == 200 || res.data.code == 200) {
            this.getbasicInformation()

            this.$message.success('保存成功')
          }
        })
      }
    },
    // 分包商类型
    getInvestigateType() {
      getInvestigateType().then((res) => {
        this.invesList = this.digui(res.data)
      })
    },
    digui(list) {
      let r = []
      list.map((v) => {
        let r2 = this.$clone(v)
        r2.disabled = false
        if (v.children && v.children.length) {
          let list = this.digui(v.children)
          if (list.length) {
            r2.children = list
          } else {
            r2.children = []
          }
        }
        r.push(r2)
      })
      return r
    },
    // 查询合格分包商
    getLaborSubcontractors() {
      if (this.loadingState.isQuality) return
      this.loadingState.isQuality = true
      getLaborSubcontractors({ status: '0', ...this.searchQueryQul })
        .then((res) => {
          this.loadingState.isQuality = false
          this.qultotal = res.totalSize
          this.dataListQul = res.data
        })
        .catch(() => {
          this.loadingState.isQuality = false
        })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    // 选择推荐分包商
    selectSub() {
      let arrs = []
      let arr = []
      if (this.RecomSubselectedRows.list) {
        this.RecomSubselectedRows.list.forEach((item) => {
          arrs.push({ id: item.id })
          arr.push(item.id)
        })
      }
      this.form = {
        ...this.form,
        list: arrs,
        subcontractorsType: arr,
        contractorId: this.RecomSubselectedRows.id,
        subcontractorName: this.RecomSubselectedRows.recommendSubcontractors,
        branchCompany: this.RecomSubselectedRows.branchCompany,
        branchCompanyId: this.RecomSubselectedRows.branchCompanyId,
        isQuality: false
      }
      this.visible = false
    },
    // 确认合格分包商
    handleOkQul() {
      let arrs = []
      let arr = []
      if (this.qulRecomSubselectedRows.typeList) {
        this.qulRecomSubselectedRows.typeList.forEach((item) => {
          arrs.push({ id: item.id })
          arr.push(item.id)
        })
      }
      this.form = {
        ...this.form,
        list: arrs,
        subcontractorsType: arr,
        // list: [{id:this.qulRecomSubselectedRows.subcontractorsId}],
        // subcontractorsType: this.qulRecomSubselectedRows.type !== null ? [this.qulRecomSubselectedRows.type] : [],
        contractorId: this.qulRecomSubselectedRows.id,
        subcontractorName: this.qulRecomSubselectedRows.subcontractors,
        branchCompany: this.qulRecomSubselectedRows.branch,
        branchCompanyId: this.qulRecomSubselectedRows.branchId,
        isQuality: true,
        qulSurveyId: this.qulRecomSubselectedRows.surveyId, //合格分包商带出来的考察id,
        investigateType: this.qulRecomSubselectedRows.investigateType,
        ledgerId: this.qulRecomSubselectedRows.id
      }
      this.memberList = this.qulRecomSubselectedRows.memberList
      this.qulVisible = false
      // this.$nextTick(() => {
      //   this.$refs.ruleForm.validate()
      // })
    },
    // 重置
    getReset() {
      this.searchQuery = {
        status: 2,
        pageNo: 1,
        pageSize: 10
      }
      this.getSubcontractorsLists()
    },
    choiceRecommand() {
      this.visible = true
      this.title = '选择推荐分包商'
      this.getSubcontractorsLists()
    },
    choiceQualified() {
      this.qulVisible = true
      this.title = '选择合格分包商'
      this.getLaborSubcontractors()
    },
    check() {
      //验证子组件是否有内容填写错误
      const validInfo = this.childValidInfo.validate()
      if (!validInfo.valid) {
        this.$message.warn(validInfo.message)
        return false
      }
      this.isSaveDraft = true
      return true
    },
    preSave() {
      if (!this.check()) return
      this.isSubmitOrSave = 'save'
      this.submit()
    },
    preSubmit() {
      this.isSubmitOrSave = 'submit'
      if (this.type === 'kaocha') {
        this.submitStep4()
      } else {
        if (!this.check()) return
        this.submit()
      }
    },
    async check2() {
      return new Promise((resolve) => {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            if (!this.form.investigateType) {
              this.$message.error('请选择考察类型')
              this.nextSteps = '1'
              resolve(false)
            } else {
              this.form.investigateId = this.id
              if (this.form.investigateType == '3') {
                this.form.investigateType = '劳务/专业分包商考察'
              } else if (this.form.investigateType == '1') {
                this.form.investigateType = '服务类分包商考察'
              } else if (this.form.investigateType == '2') {
                this.form.investigateType = '甲指分包商考察'
              }
              let groupLeader = []
              groupLeader = this.memberList?.filter((item) => item.type == '1') || []
              if (groupLeader.length == 0) {
                this.$message.error('请选择考察小组组长')
                resolve(false)
              } else if (groupLeader.length > 1) {
                this.$message.error('只能选择一个考察小组组长')
                resolve(false)
              } else {
                this.form.memberList = this.memberList
                if (this.id) {
                  resolve('edit')
                } else {
                  let data = {
                    subcontractorName: this.form.subcontractorName,
                    investigateType: this.form.investigateType,
                    branchCompanyId: this.form.branchCompanyId,
                    addOrEdit: this.idAddEdit
                  }
                  let res = await istheSameInvestigate(data)
                  if (res.data == 1) {
                    this.$message.error('该分公司下已存在此分包商考察')
                    resolve(false)
                  } else if (res.data == 0) {
                    resolve('add')
                  }
                }
              }
            }
          } else {
            this.$noticeWarning('请填写完整')
            resolve(false)
          }
          this.loadingSubmit = this.loadingSave = false
        })
      })
    },
    async submitAudit(id) {
      this.loading = true
      let res = await updateSubStatus({ id: id || this.id })
      this.loadingSubmit = this.loadingSave = false
      this.loading = false
      if (res.code === 200) {
        this.$message.success('提交成功')
        if(this.type == 'kaocha'){
          this.businessId = res.data.id || this.id;
          this.setProcessConfig = this.processConfig

        }else{
          this.$close()
        }
         
      }
    },
    async submit() {
      this.loading = true
      if (this.nextSteps == '1') {
        let r = await this.check2()
        if (!r) return (this.loading = false)
        let resItem
        if (r === 'add') resItem = await addbasicInformation(this.form)
        if (r === 'edit') resItem = await editbasicInformation(this.form)
        if (resItem.code === 200) {
          this.id = resItem.data.investigateId
          if (this.isSubmitOrSave === 'save') {
            this.$message.success('保存成功')
          } else if (this.isSubmitOrSave === 'submit') {
            await this.submitAudit()
          }
        }
        this.loading = false
      } else if (this.nextSteps === '2') {
        this.loading = true
        let res
        let result = this.$refs.serverRef.serviceList || this.$refs.serverRef.fingernailList || this.$refs.serverRef.labourList || []
        if (result.subType === '服务类分包商考察') {
          result.investigateTypeCode = '1'
          res = await editInformatinService(result)
        } else if (result.subType === '甲指分包商考察') {
          result.investigateTypeCode = '2'
          res = await editfingernailList(result)
        } else if (result.subType === '劳务/专业分包商考察') {
          result.investigateId = this.id
          result.investigateTypeCode = '3'
          res = await editlabourList(result)
        }
        if (res.code === 200) {
          await this.getbasicInformation()
          if (this.isSubmitOrSave === 'save') {
            this.$message.success('保存成功')
          } else if (this.isSubmitOrSave === 'submit') {
            await this.submitAudit()
          }
        }
        this.loading = false
      } else if (this.nextSteps == '3') {
        this.loading = true
        if (this.isSubmitOrSave === 'save') {
          this.$message.success('保存成功')
        } else if (this.isSubmitOrSave === 'submit') {
          await this.submitAudit()
        }
        this.loading = false
      } else if (this.nextSteps == '4') {
        this.submitStep4()
      }
    },
    submitStep4() {
      this.loading = false
      this.setProcessConfig = null
      this.$refs.ruleForm2.validate(async (valid) => {
        if (valid) {
          this.loading = true
          let r = this.scoreList.every((v) => v.situation)
          if (!r) {
            this.loading = false
            return this.$noticeWarning('请填写完整')
          }
          let data = {
            baseId: this.id,
            inspectionSuggestion: this.form.inspectionSuggestion,
            progressReviews: this.scoreList.map((v) => {
              let r2 = this.scoreColumns.find((w) => w.title === '考察内容')
              if (r2) {
                v.content = v[r2.dataIndex]
              }
              let r3 = this.scoreColumns.find((w) => w.title === '考察要求')
              if (r3) {
                v.demand = v[r3.dataIndex]
              }
              return v
            }),
            subUnitLevel: this.form.subUnitLevel
          }

        //console.log(this.businessId,'businessId')
        // this.setProcessConfig = this.processConfig
          let res = await editSituation(data)
          this.loading = false
          if (res.code === 200 || res.data.code === 200) {
            if (this.isSubmitOrSave === 'submit') {
              await this.submitAudit()
            } else {
              this.$noticeSuccess('保存成功')
            }
          }
        } else {
          this.$noticeWarning('请填写完整')
        }
      })
    },
    // 切换考察类型
    changeType(value) {
      if (value == '1') {
        this.form.investigateType = '服务类分包商考察'
        this.serviceList.subType = '服务类分包商考察'
      } else if (value == '2') {
        this.form.investigateType = '甲指分包商考察'
        this.fingernailList.subType = '甲指分包商考察'
      } else if (value == '3') {
        this.form.investigateType = '劳务/专业分包商考察'
        this.labourList.subType = '劳务/专业分包商考察'
      }
      if (this.form.investigateType == this.form.oldInvestigateType || !this.form.oldInvestigateType) {
      } else {
        if (this.form.investigateType != this.form.oldInvestigateType) {
          this.$confirm({
            title: '警告提醒！',
            content: '如果切换，则已填写的考察信息将不再保存',
            okType: 'danger',
            onOk() {
              return false
            },
            onCancel() {
              return false
              if (this.form.oldInvestigateType == '服务类分包商考察') {
                this.form.oldInvestigateType = '1'
              } else if (this.form.oldInvestigateType == '甲指分包商考察') {
                this.form.oldInvestigateType = '2'
              } else if (this.form.oldInvestigateType == '劳务/专业分包商考察') {
                this.form.oldInvestigateType = '3'
              }
              this.$set(this.form, 'investigateType', this.form.oldInvestigateType)
            }
          })
        }
      }
    },
    getSubcontractorsLists() {
      if (this.loadingState.isRecomd) return
      this.loadingState.isRecomd = true
      console.log(this.searchQuery)
      getSubcontractorsLists(this.searchQuery)
        .then((res) => {
          this.loadingState.isRecomd = false
          this.total = res.totalSize
          this.dataList = res.data
        })
        .catch(() => {
          this.loadingState.isRecomd = false
        })
    },
    handleChangeCompany() {},
    // 查询第一个tab页的详情
    async getbasicInformation() {
      if (this.id) {
        this.inited = false
        this.loading = true
        let res = await getbasicInformation({ id: this.id })
        if (res.code === 200) {
          this.form = res.data
          const list = []
          this.form.typeList &&
            this.form.typeList.forEach((item) => {
              list.push(item.id)
            })
          //fix- select placeholader未展示bug
          if (!this.form.investigateType) {
            this.form.investigateType = undefined
          }
          if (!this.form.branchCompanyId) {
            this.form.branchCompanyId = undefined
          }
          this.form = {
            ...this.form,
            subcontractorsType: list
          }
          this.memberList = this.form.memberList
          await this.getScoreData()
          // this.getScoreData2()
          setTimeout(() => {
            this.inited = true
          }, 300)
        }
        this.loading = false
      }
    },
    onChange(value) {},
    RecomSubonSelectChange(selectedRowKeys, selectedRows) {
      this.RecomSubselectedRowKeys = selectedRowKeys
      this.RecomSubselectedRows = selectedRows[0]
    },
    qulRecomSubonSelectChange(selectedRowKeys, selectedRows) {
      this.qulRecomSubselectedRowKeys = selectedRowKeys
      this.qulRecomSubselectedRows = selectedRows[0]
    },
    getCheckboxProps: (record) => ({
      props: {
        // 全部默认禁止选中
        disabled: true,
        // 某几项默认禁止选中(R: 当state等于1时)
        // disabled: record.state == 1,
        // 某几项默认选中(R: 当state等于1时)
        defaultChecked: record.state == 1
      }
    }),
    employeeNums(val) {
      this.employeeNum = val
    },
    getSub(resItem) {
      let id = this.form.qulSurveyId || this.id
      //选择合格分包商
      if (resItem.data.investigateTypeCode == '1') {
        // 服务
        getServiceInformation({ id }).then((res) => {
          this.serviceList = res.data
          this.serviceList.subcontractorId = res.data.subcontractorId
          this.serviceList.surveyId = resItem.data.investigateId
          this.serviceList.subType = '服务类分包商考察'
        })
      }
      // 甲指
      if (resItem.data.investigateTypeCode == '2') {
        getfingernailList({ id }).then((res) => {
          this.fingernailList = res.data
          this.fingernailList.subcontractorId = res.data.subcontractorId
          this.fingernailList.surveyId = resItem.data.investigateId
          this.fingernailList.subType = '甲指分包商考察'
        })
      }
      // 劳务
      if (resItem.data.investigateTypeCode == '3') {
        getlabourService({ id }).then((res) => {
          this.labourList = res.data
          this.labourList.subcontractorId = res.data.subcontractorId
          this.labourList.surveyId = resItem.data.investigateId
          this.labourList.subType = '劳务/专业分包商考察'
        })
      }
    },

    // 从第一步到第二歩  验证必填项
    // 从第三歩到第二歩  不需验证必填项
    async callback(key) {
      // tabs切换
      this.nextSteps = key
      if (key === '1') {
        this.getbasicInformation() // 更新数据，避免oldInvestigateType字段在标签页来回切换时更新不及时的问题
      }
      if (this.type == 'add') {
        if (this.nextSteps == 2) {
          this.loading = true
          let r = await this.check2()
          if (!r) {
            this.loading = false
            return (this.nextSteps = '1')
          }
          let resItem
          if (r === 'add') {
            resItem = await addbasicInformation(this.form)
            this.idAddEdit = 1
            if (resItem.code === '200') {
              this.nextSteps = '2'
              this.id = resItem.data.investigateId
              sessionStorage.setItem('addInvestigateId', JSON.stringify(resItem.data.investigateId))
              // 判断是选择的推荐分包商还是合格分包商
              this.getSub(resItem)
            }
          }
          if (r === 'edit') {
            resItem = await editbasicInformation(this.form)
            if (resItem.code === 200) {
              this.nextSteps = '2'
              this.getSub(resItem)
            }
          }
          this.loading = false
        }
        if (this.nextSteps == 3) {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              this.form.memberList = this.memberList
              this.form.memberList.forEach((item) => {
                item.id = null
              })
              if (this.id) {
                this.form.investigateId = this.id
                editbasicInformation(this.form).then((res) => {
                  if (res.code == 200) {
                    if (this.form.investigateType == '1' || this.form.investigateType == '服务类分包商考察') {
                      this.getsubmitNext()
                    }
                    if (this.form.investigateType == '2' || this.form.investigateType == '甲指分包商考察') {
                      this.getsubmitNextSteps()
                    }
                    if (this.form.investigateType == '3' || this.form.investigateType == '劳务/专业分包商考察') {
                      this.getsubmitNextStep()
                    }
                  }
                })
              } else {
                let data = {
                  subcontractorName: this.form.subcontractorName,
                  investigateType: this.form.investigateType,
                  branchCompanyId: this.form.branchCompanyId,
                  addOrEdit: this.idAddEdit
                }
                istheSameInvestigate(data).then((res) => {
                  if (res.data == 1) {
                    this.$message.error('该分公司下已存在此分包商考察')
                    this.nextSteps = '1'
                  } else if (res.data == 0) {
                    addbasicInformation(this.form).then((resItem) => {
                      this.idAddEdit = 1
                      if (resItem.code == '200') {
                        this.nextSteps = '2'
                        this.id = resItem.data.investigateId
                        sessionStorage.setItem('addInvestigateId', JSON.stringify(resItem.data.investigateId))
                        this.getSub(resItem)
                      }
                    })
                  }
                })
              }
            } else {
              this.nextSteps = '1'
            }
          })
        }
        if (this.nextSteps == '1') {
          this.nextSteps == '1'
        }
      } else if (this.type == 'edit') {
        //编辑
        if (this.nextSteps == 2) {
          console.log(this.id)
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              if (!this.form.investigateType) {
                this.$message.error('请选择考察类型')
                this.nextSteps = '1'
              } else {
                this.form.investigateId = this.id
                if (this.form.investigateType == '3') {
                  this.form.investigateType = '劳务/专业分包商考察'
                } else if (this.form.investigateType == '1') {
                  this.form.investigateType = '服务类分包商考察'
                } else if (this.form.investigateType == '2') {
                  this.form.investigateType = '甲指分包商考察'
                }
                let arr = []
                this.memberList.forEach((item) => {
                  arr = this.memberList.filter((items) => items.type == '1')
                  item.id = null
                })
                if (arr.length == 0) {
                  this.$message.error('请选择考察小组组长')
                  return false
                } else if (arr.length > 1) {
                  this.$message.error('只能选择一个考察小组组长')
                  return false
                } else {
                  this.form.memberList = this.memberList
                  this.form.investigateId = this.id

                  editbasicInformation(this.form).then((resItem) => {
                    this.idAddEdit = 1
                    if (resItem.code == 200) {
                      sessionStorage.setItem('addInvestigateId', JSON.stringify(resItem.data.investigateId))

                      this.nextSteps = '2'
                      // 判断是选择的推荐分包商还是合格分包商
                      this.getSub(resItem)
                    }
                  })
                }
              }
            } else {
              this.nextSteps = '1'
            }
          })
        }
        if (this.nextSteps == 3) {
          if (this.form.investigateType == '1' || this.form.investigateType == '服务类分包商考察') {
            this.getsubmitNext()
          }
          if (this.form.investigateType == '2' || this.form.investigateType == '甲指分包商考察') {
            this.getsubmitNextSteps()
          }
          if (this.form.investigateType == '3' || this.form.investigateType == '劳务/专业分包商考察') {
            this.getsubmitNextStep()
          }
        }
        if (this.nextSteps == 1) {
          this.nextSteps == '1'
        }
      } else if (this.type != 'add' || this.type != 'edit') {
        this.loading = true
        let resItem = await editbasicInformation(this.form)
        this.getSub(resItem)
        this.loading = false
      }
    },
    getPopupContainer(triggerNode) {
      return triggerNode.parentNode
    },
    handleCancel() {
      this.visible = false
    },
    handleCancelQul() {
      this.qulVisible = false
    },
    async nextStep() {
      let steps = this.nextSteps
      console.log('type', this.type)
      if (this.type == 'add') {
        if (steps == '1') {
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              if (!this.form.investigateType) {
                this.$message.error('请选择考察类型')
                this.nextSteps = '1'
              } else {
                this.form.investigateId = this.id
                if (this.form.investigateType == '3') {
                  this.form.investigateType = '劳务/专业分包商考察'
                } else if (this.form.investigateType == '1') {
                  this.form.investigateType = '服务类分包商考察'
                } else if (this.form.investigateType == '2') {
                  this.form.investigateType = '甲指分包商考察'
                }
                let groupLeader = []
                groupLeader = this.memberList.filter((item) => item.type == '1')
                if (groupLeader.length == 0) {
                  this.$message.error('请选择考察小组组长')
                  return false
                } else if (groupLeader.length > 1) {
                  this.$message.error('只能选择一个考察小组组长')
                  return false
                } else {
                  let data = {
                    subcontractorName: this.form.subcontractorName,
                    investigateType: this.form.investigateType,
                    branchCompanyId: this.form.branchCompanyId,
                    addOrEdit: this.idAddEdit
                  }
                  this.loading = true
                  if (this.id) {
                    //新增后编辑
                    this.form.memberList = this.memberList
                    this.form.investigateId = this.id
                    this.form.memberList.forEach((item) => {
                      item.id = null
                    })
                    editbasicInformation(this.form).then((resItem) => {
                      this.loading = false
                      this.idAddEdit = 1
                      if (resItem.code == '200') {
                        this.nextSteps = '2'
                        this.id = resItem.data.investigateId
                        sessionStorage.setItem('addInvestigateId', JSON.stringify(resItem.data.investigateId))

                        if (resItem.data.investigateTypeCode == '1') {
                          // 服务
                          getServiceInformation({ id: this.id }).then((res) => {
                            this.serviceList = res.data
                            this.serviceList.subcontractorId = res.data.subcontractorId
                            this.serviceList.subType = '服务类分包商考察'
                          })
                        }
                        // 甲指
                        if (resItem.data.investigateTypeCode == '2') {
                          getfingernailList({ id: this.id }).then((res) => {
                            this.fingernailList = res.data
                            this.fingernailList.subcontractorId = res.data.subcontractorId
                            this.fingernailList.subType = '甲指分包商考察'
                          })
                        }
                        // 劳务
                        if (resItem.data.investigateTypeCode == '3') {
                          getlabourService({ id: this.id }).then((res) => {
                            this.labourList = res.data
                            this.labourList.subcontractorId = res.data.subcontractorId
                            this.labourList.subType = '劳务/专业分包商考察'
                          })
                        }
                      } else {
                        this.nextSteps = '1'
                      }
                    })
                  } else {
                    //编辑
                    istheSameInvestigate(data).then((res) => {
                      this.loading = false
                      //去重
                      if (res.data == 1) {
                        this.$message.error('该分公司下已存在此分包商考察')
                        this.nextSteps = '1'
                      } else if (res.data == 0) {
                        this.form.memberList = this.memberList
                        this.form.memberList.forEach((item) => {
                          item.id = null
                        })
                        this.loading = true
                        addbasicInformation(this.form).then((resItem) => {
                          this.loading = false
                          this.idAddEdit = 1
                          if (resItem.code == '200') {
                            this.nextSteps = '2'
                            this.id = resItem.data.investigateId
                            sessionStorage.setItem('addInvestigateId', JSON.stringify(resItem.data.investigateId))

                            if (resItem.data.investigateTypeCode == '1') {
                              // 服务
                              this.loading = true
                              getServiceInformation({ id: this.id }).then((res) => {
                                this.loading = false
                                this.serviceList = res.data
                                this.serviceList.subcontractorId = resItem.data.subcontractorId
                                this.serviceList.surveyId = resItem.data.investigateId
                                this.serviceList.subType = '服务类分包商考察'
                              })
                            }
                            // 甲指
                            if (resItem.data.investigateTypeCode == '2') {
                              this.loading = true
                              getfingernailList({ id: this.id }).then((res) => {
                                this.loading = false
                                this.fingernailList = res.data
                                this.fingernailList.subcontractorId = resItem.data.subcontractorId
                                this.fingernailList.surveyId = resItem.data.investigateId
                                this.fingernailList.subType = '甲指分包商考察'
                              })
                            }
                            // 劳务
                            if (resItem.data.investigateTypeCode == '3') {
                              this.loading = true
                              getlabourService({ id: this.id }).then((res) => {
                                this.loading = false
                                this.labourList = res.data
                                this.labourList.subcontractorId = resItem.data.subcontractorId
                                this.labourList.surveyId = resItem.data.investigateId
                                this.labourList.subType = '劳务/专业分包商考察'
                              })
                            }
                          } else {
                            this.nextSteps = '1'
                          }
                        })
                      }
                    })
                  }
                }
              }
            }
          })
        }
      } else if (this.type == 'edit') {
        console.log('edit')
        if (steps == '1') {
          console.log('222')
          this.$refs.ruleForm.validate((valid) => {
            if (valid) {
              console.log('4')
              if (!this.form.investigateType) {
                this.$message.error('请选择考察类型')
                this.nextSteps = '1'
              } else {
                this.form.investigateId = this.id
                if (this.form.investigateType == '3') {
                  this.form.investigateType = '劳务/专业分包商考察'
                } else if (this.form.investigateType == '1') {
                  this.form.investigateType = '服务类分包商考察'
                } else if (this.form.investigateType == '2') {
                  this.form.investigateType = '甲指分包商考察'
                }
                let groupLeader = []
                groupLeader = this.memberList.filter((item) => item.type == '1')
                if (groupLeader.length == 0) {
                  this.$message.error('请选择考察小组组长')
                  return false
                } else if (groupLeader.length > 1) {
                  this.$message.error('只能选择一个考察小组组长')
                  return false
                } else {
                  this.form.memberList = this.memberList
                  this.form.investigateId = this.id
                  this.form.memberList.forEach((item) => {
                    item.id = null
                  })
                  console.log(this.form)
                  this.loading = true
                  editbasicInformation(this.form).then((resItem) => {
                    this.loading = false
                    this.idAddEdit = 1
                    if (resItem.code == '200') {
                      this.nextSteps = '2'
                      this.id = resItem.data.investigateId

                      sessionStorage.setItem('addInvestigateId', JSON.stringify(resItem.data.investigateId))

                      if (resItem.data.investigateTypeCode == '1') {
                        // 服务
                        this.loading = true
                        getServiceInformation({ id: this.id }).then((res) => {
                          this.loading = false
                          this.serviceList = res.data
                          this.serviceList.subcontractorId = res.data.subcontractorId
                          this.serviceList.subType = '服务类分包商考察'
                        })
                      }
                      // 甲指
                      if (resItem.data.investigateTypeCode == '2') {
                        this.loading = true
                        getfingernailList({ id: this.id }).then((res) => {
                          this.loading = false
                          this.fingernailList = res.data
                          this.fingernailList.subcontractorId = res.data.subcontractorId
                          this.fingernailList.subType = '甲指分包商考察'
                        })
                      }
                      // 劳务
                      if (resItem.data.investigateTypeCode == '3') {
                        this.loading = true
                        getlabourService({ id: this.id }).then((res) => {
                          this.loading = false
                          this.labourList = res.data
                          this.labourList.subcontractorId = res.data.subcontractorId
                          this.labourList.subType = '劳务/专业分包商考察'
                        })
                      }
                    } else {
                      this.nextSteps = '1'
                    }
                  })
                }
              }
            }
          })
        }
        if (steps == '3') {
          this.nextSteps = '4'
        }
      } else if (this.type == 'view' || this.type == 'kaocha' || this.type != 'approve') {
        if (steps == '1') {
          let resItem = await editbasicInformation(this.form)
          this.getSub(resItem)
          this.nextSteps = '2'
        } else if (steps == '2') {
          this.nextSteps = '3'
        } else if (steps == '3') {
          this.nextSteps = '4'
        }
      }
    },
    goBack() {
      if (this.id && this.type == 'add') {
        if (this.isSaveDraft == true) {
          this.$close()
        } else {
          this.$confirm({
            title: '警告提醒！',
            content: '是否删除当前数据？',
            okType: 'danger',
            onOk: () => {
              deleteSub({ id: this.id }).then((res) => {
                if (res.code === 200) {
                  this.$message.success('删除成功')
                  let addInvestigateId = JSON.parse(sessionStorage.getItem('addInvestigateId'))
                  if (addInvestigateId) {
                    sessionStorage.removeItem('addInvestigateId')
                  }
                  this.$close()
                }
              })
            }
          })
        }
      } else {
        this.$close()
      }
    },
    async getOrgUsers(val, loadFlag = '') {
      if (this.loadingUser) return
      this.loadingUser = true
      if (loadFlag === 'more') {
        this.pageNumber = this.pageNumber + 1
      } else {
        this.pageNumber = 1
        this.totalPages = 0
        this.groupLists = []
      }
      let res = await getEmployeesList({
        nameLike: val ? val : '',
        queryPostRelation: true,
        pageNumber: this.pageNumber,
        pageSize: this.pageSize
      })
      this.loadingUser = false
      if (res.code === 200) {
        let list = res.data || []
        this.groupLists = this.groupLists.concat(list)
        this.totalPages = res.totalPages
      }
    },
    // 下拉滚动加载
    scrollMore(e) {
      const { target } = e
      let total = target.scrollTop + target.offsetHeight
      let scrollHeight = target.scrollHeight
      // this.pageNo是当前页 this.totalPage是总页数
      if (total >= scrollHeight - 1 && total < scrollHeight + 1 && this.pageNumber <= this.totalPages) {
        this.getOrgUsers('', 'more') // 调用api方法
      }
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    getList(value, label) {},
    changeMember(value) {
      this.employee = value
      this.formAdd = {
        ...this.formAdd,
        employeeName: value.label,
        employeeId: value.key
      }

      // let list = []
      // list = this.groupLists.filter((item) => item.id == value.key)
      // let jobs = []
      // if(list[0].posts){
      //   list[0].posts.forEach((item) => {
      //     jobs.push(item.name)
      //   })
      // }

      getPosts({ id: value.key }).then((res) => {
        let arrys = res.data
        let postArr = []
        if (arrys && arrys.length > 0) {
          arrys.forEach(function (obj, i) {
            postArr.push(obj.pname)
          })
        }
        this.formAdd.post = postArr.join(',')
        this.visibleGroup = true

        this.$nextTick(() => {
          this.$refs.createModal.validateField('employeeId')
        })
      })
    },
    staffSelectedValue(val) {},
    search() {
      this.$refs.table.refresh(true)
    },
    goDel() {
      console.log(this.selectedRows)
      if (this.selectedRowKeys.length == 0) {
        this.$message.error('请先选择需要删除的成员！')
        return
      } else {
        let _this = this
        _this.$confirm({
          title: '警告提醒！',
          content: '确定删除所选成员？',
          okType: 'danger',
          onOk() {
            _this.memberList = _this.memberList.filter((item) => {
              return !_this.selectedRowKeys.includes(item.employeeId)
            })
            _this.$message.success('删除成功！')
            _this.selectedRows = []
            _this.selectedRowKeys = []
          },
          onCancel() {
            console.log('取消删除')
          }
        })
      }
    },
    handleEditGroup(record, index) {
      this.titles = '编辑考察小组成员'
      this.visibleGroup = true
      this.editTargetIndex = index
      this.ifReplace = 1
      this.employee = {
        label: record.employeeName,
        value: record.employeeId
      }
      this.formAdd = { ...record }
      // this.formAdd.post = this.formAdd.post.split(",")
      this.employee = {
        label: record.employeeName,
        value: record.employeeId
      }
    },

    goAdd() {
      this.titles = '新增考察小组成员'
      this.editTargetIndex = null // 重置序号
      this.ifReplace = null // 重置编辑标识
      this.visibleGroup = true
      this.employee = undefined
      this.formAdd = {}
      this.formAdd.post = ''
    },
    // 确认考察小组成员
    handleOk() {
      this.$refs.createModal.validate((valid) => {
        if (!valid) return

        if (this.memberList != null) {
          const targetData = this.memberList[this.editTargetIndex] || null // 当前操作的目标对象
          const isLeader = targetData && targetData.type === '1' // 当前操作目标对象是否为组长

          // 校验人员是否存在于小组
          if (
            this.memberList.some((item) => {
              if (targetData) {
                // 如果targetData存在，则需绕过targetData.employeeId代表的人（目的是，在编辑验重时，将原数据的人员排除在外）
                return targetData.employeeId !== this.formAdd.employeeId && item.employeeId === this.formAdd.employeeId
              }
              return item.employeeId === this.formAdd.employeeId
            })
          ) {
            this.$message.warning('此人员已存在于小组！')
            return
          }
          // 验证是否有组长（如果目标对象是组长，则无需校验；如果目标对象不是组长，则查询列表中是否已经存在组长）
          if (!isLeader) {
            const leaderIndex = this.memberList.findIndex((item) => item.type === '1')
            if (leaderIndex > -1 && this.formAdd.type === '1') {
              this.$message.warning('只能选择一个考察小组组长')
              return
            }
          }
        }

        this.visibleGroup = false

        // 资源考察编辑
        if (this.id) {
          if (!this.memberList) {
            this.memberList = []
          }
          if (this.ifReplace == 1) {
            this.memberList.splice(this.editTargetIndex, 1, { ...this.formAdd })
            this.editTargetIndex = null
          } else {
            this.memberList.push(this.formAdd)
            let newMembers = this.reduceData(this.memberList)
            this.memberList = newMembers
          }
        } else {
          // 考察新增
          if (this.ifReplace == 1) {
            this.memberList.splice(this.editTargetIndex, 1, { ...this.formAdd })
            this.editTargetIndex = null
          } else {
            let arrys = []
            if (this.memberList == null) {
              arrys = [this.formAdd]
            } else {
              arrys = this.memberList.concat(this.formAdd)
            }

            this.memberList = this.reduceData(arrys)
          }
        }
      })
    },
    reduceData(arr) {
      var result = []
      var obj = {}
      for (var i = 0; i < arr.length; i++) {
        if (!obj[arr[i].employeeId]) {
          result.push(arr[i])
          obj[arr[i].employeeId] = true
        }
      }
      return result
    },
    handleCancelGroup() {
      this.visibleGroup = false
    }
  }
}
</script>

<style lang="less" scoped>
.ttt {
  /deep/ .ant-form-item-control-wrapper {
    width: 100%;
  }
}

.wrapper-row {
  padding-left: 55px;
  font-weight: bold;
  letter-spacing: 1px;
}

/deep/ .ant-btn {
  border-radius: 5px;
}

// /deep/ .ant-calendar-picker-input.ant-input {
//   width: 100%;
// }

/deep/ .ant-input {
  /*width: 70%;*/
  border-radius: 5px;
}

// /deep/ .ant-calendar-picker {
//   width: 100%;
//   border-radius: 5px;
// }

/deep/ .ant-card.ant-card-bordered {
  border-radius: 5px;
}

.ant-avatar-lg {
  width: 48px;
  height: 48px;
  line-height: 48px;
}

.list-content-item {
  color: rgba(0, 0, 0, 0.45);
  display: inline-block;
  vertical-align: middle;
  font-size: 14px;
  margin-left: 40px;

  span {
    line-height: 20px;
  }

  p {
    margin-top: 4px;
    margin-bottom: 0;
    line-height: 22px;
  }
}

.title-name {
  border-left: 5px solid #1890ff;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 20px;
  padding-left: 15px;
  height: 20px;
  line-height: 20px;
}

/deep/ .table-page-search-wrapper .ant-form-inline .ant-row .ant-col.ant-col-sm-24.ant-col-md-12 {
  padding-left: 80px;
}

/deep/ .ant-card-bordered {
  margin-top: 60px;
}

/deep/ .ant-table-pagination.ant-pagination {
  display: none;
}
</style>
